import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "@/store";
import instance from "@/request/request";
import {listToTree} from "@/util/treeUtil";

Vue.use(VueRouter)

//路由列表
const routes = [
  {
    path: '/',
    name: 'mainLayout',
    redirect: '/home',
    component: () => import('@/views/common/MainLayout'),
    children: [
      {
        path:'/infor',
        component:()=>import('@/views/Infor.vue')
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/components/LoginView')
  }
]
const router = new VueRouter({
  routes,
  mode: 'history',
})

// 路由守卫 拦截一些非法路径的访问
router.beforeEach(async (to,from,next)=>{
  let token = window.sessionStorage.getItem("token");
  if(!token&&to.path=="/login"){
    next()
    return;
  }
  if(token&&to.path=="/login"){
    next('/')
    return;
  }
  if(!token&&to.path!='/login'){
    next("/login")
    return;
  }
  if(store.state.menulist.length==0){
     const {data}=await instance.get("/user/getmenulist")
    const menuList= data.map(dt=>{
      if(dt.isMenu==0){
        return{
          title:dt.title,
          id:dt.id,
          pid:dt.pid,
          icon:dt.icon
        }
      }
       return {
         title:dt.title,
         id:dt.id,
         pid:dt.pid,
         icon:dt.icon,
         path:dt.path
       }
      })
    const list=[{title: '首页', path: '/home'},...listToTree(menuList)]
    store.commit('getMenuList',list)
    //设置动态路由
    let res=data.filter(dt=>dt.isMenu==1).map(s=>{
      return{
        path:s.path,
        component: () => import('@/views/' + s.component)
      }
    })
    let newRouter = [
      {path: '/home', component: () => import('@/views/HomeView')},
      ...res,
      {path: '/*', component: () => import('@/views/Page404View')}
    ]
    //  遍历新路由 实现路由的动态添加
    newRouter.forEach(nrt=>{
      router.addRoute("mainLayout",nrt)
    })
    next(to.path)
    return
  }
  next()
})

export default router
